package com.autologistics.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.autologistics.model.Disparter;
import com.autologistics.model.Machine;

public class MachineDaoImpl implements MachineDao{
	HibernateTemplate hibTemplate;

	public HibernateTemplate getHibTemplate() {
		return hibTemplate;
	}

	public void setHibTemplate(HibernateTemplate hibTemplate) {
		this.hibTemplate = hibTemplate;
	}
	/**
	 * @return �ն��б� or null 
	 * @author cl
	 */
	public List<Machine> listAll(){
		String hql="from Machine";
		List<Machine> list = hibTemplate.find(hql);
		if (!list.isEmpty()){
			return list;
		}else{
			return null;
		}
	}
	public List<Machine> listByState(int state){
		String hql="from Machine where state=?";
		List<Machine> list = hibTemplate.find(hql,state);
		if (!list.isEmpty()){
			return list;
		}else{
			return null;
		}
	}
	/**
	 * @param id
	 * @return ��������
	 */
	public Machine getById(int id){
		String hql="from Machine where id=?";
		List<Machine> list = hibTemplate.find(hql,id);
		if (!list.isEmpty()){
			return list.get(0);
		}else{
			return null;
		}
	}
	/**
	 * @param id
	 * @return ��������
	 */
	public Machine getByAddressId(int id){
		String hql="from Machine where address=?";
		List<Machine> list = hibTemplate.find(hql,id);
		if (!list.isEmpty()){
			return list.get(0);
		}else{
			return null;
		}
	}

	@Override
	public Machine getByIDAddress(String ip) {
		// TODO Auto-generated method stub
		String hql="from Machine where ipAddress=?";
		List<Machine> list = hibTemplate.find(hql,ip);
		if (!list.isEmpty()){
			return list.get(0);
		}else{
			return null;
		}
	}

	@Override
	public void updata(Machine machine) {
		// TODO Auto-generated method stub
		hibTemplate.update(machine);
	}

	@Override
	public void add(Machine machine) {
		// TODO Auto-generated method stub
		hibTemplate.save(machine);
	}
	public List<Machine> queryForOnePage(final int offset, final int length){
		String hql = "from Machine";
		Session session = hibTemplate.getSessionFactory().openSession();
		Query q = session.createQuery(hql);  
	    q.setFirstResult(offset);  
	    q.setMaxResults(length); 
	    List<Machine> list=q.list();
	    session.close();
		if (!list.isEmpty()){
			return list;
		}else{
			return null;
		}
	}

	@Override
	public List<Machine> listNotOffline() {
		String hql="from Machine where state<>4";
		List<Machine> list = hibTemplate.find(hql);
		if (!list.isEmpty()){
			return list;
		}else{
			return null;
		}
	}
}
